package com.apps.realtyportal;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import mapviewballoons.example.custom.CustomItemizedOverlay;
import mapviewballoons.example.custom.CustomOverlayItem;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import sample.classes.ActionItem;
import sample.classes.QuickAction;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.apps.essentials.AddTapLocationOverlay;
import com.apps.essentials.AddTapLocationOverlay2;
import com.apps.essentials.AddUserLocationOverlay;
import com.apps.essentials.AlertDialogManager;
import com.apps.essentials.CheckConnection;
import com.apps.essentials.ConsumeWebService;
import com.apps.mapsettings.Help;
import com.apps.mapsettings.MapSettings;
import com.apps.routing.GoogleParser;
import com.apps.routing.Parser;
import com.apps.routing.RouteOverlay;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.jason.apps.buyer.Buyer;
import com.jason.apps.dashboard.DashBoard;
import com.jason.apps.fromdashboard.Agent;
import com.apps.essentials.ComputeDistance;
import com.apps.realtyportal.MultipleSearching2.Exchanger;
import com.apps.routing.Route;

public class HomeActivity extends SherlockFragmentActivity implements
		OnClickListener {
	ActionBar ab = null;
	private ActionBar actionbar;
	private Button spinnerIcon;
	private Button _logIn, _logout;
	private Button logo;
	public static boolean determineLogine = false;
	private static final int ID_UP = 1;
	private static final int ID_DOWN = 2;
	private static final int ID_SEARCH = 3;
	private static final int ID_INFO = 4;
	private static final int ID_ERASE = 5;
	private static final int ID_OK = 6;
	private static final int AUTO_SEARCH = 1;
	private static final int DIRECTION = 2;
	private static final int BOOKMARKS= 3;
	private static final int HELP = 4;	 
	private boolean useLogo = false;
	private boolean showHomeUp = false;
	String string = "Property Portal";
	String[] actions = new String[] { "Property Portal", "Bookmark",
			"Subscribe", "Share" };
	String[] entries = new String[] { "Property Portal", "View Card",
			"Favorites", "Settings" };
	int count;
	private Spinner mySpinner;
	private MapFragment mMapFragment;
	private Fragment mVisible = null;
	private EditText location_searching;
	private Button btn_searching;
	private Context _context;
	// start here checking connection
	CheckConnection cc;
	Boolean isconnected = false;
	// start variable autosearching
	int minLat = Integer.MAX_VALUE;
	int minLong = Integer.MAX_VALUE;
	int maxLat = Integer.MIN_VALUE;
	int maxLong = Integer.MIN_VALUE;

	private static double lat;

	private static double lon;

	private int latE6;

	private int lonE6;
	private GeoPoint gp;
	private Drawable drawable;

	private Drawable drawable1, drawable2;

	private boolean foodIsDisplayed = false;
	private static MapController controlmap;
	ConsumeWebService cws;
	AddTapLocationOverlay taplocation;
	OverlayItem overlayitem;
	MyLocationOverlay overlaycurrentlocation = null;
	ProgressDialog pDialog;
	int userlat = 10309416;
	int userlon = 123893509;
	TextView tv = null;
	String address_location = null;
	String address_selected = null;
	String addr = null;

	public static final String KEY_ID = "property_id";
	public static final String KEY_NAME = "property_name";
	public static final String KEY_DESCRIPTION = "property_description";
	public static final String KEY_PRICE = "price";
	public static final String KEY_LATITUDE = "latitude";
	public static final String KEY_LONGITUDE = "longitude";
	public static final String KEY_ADDRESS = "address";
	public static final String KEY_TYPE = "type";
	public static final String KEY_IMAGE = "main_image";
	public static final String KEY_PERSONFNAME="firstname";
	public static final String KEY_PERSONLNAME="lastname";
	public static final String KEY_PERSONCONTACT="mobile";
	AsyncTask newtask;
	public static boolean islogin = false;
	String coList;
	List<Overlay> newmapOverlays;
	GeoPoint gpsource;
	GeoPoint gpdist;
	// try overlay2
	CustomOverlayItem overlayItem3;
	AddUserLocationOverlay useroverlaylocation;
	AddTapLocationOverlay2 tapoverlaylocation;
	CustomItemizedOverlay<CustomOverlayItem> newitemizedOverlay2;
	AlertDialogManager alert = new AlertDialogManager();
	public final ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
	Context appContext;
	HashMap<String, String> map;
	private MyLocationOverlay me = null;
	Handler h = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Bundle data = msg.getData();

			int latitude = data.getInt("latitude");
			int longitude = data.getInt("longitude");
			executeAutoSearch(latitude, longitude);
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// start here checking connection
		cc = new CheckConnection(getApplicationContext());
		isconnected = cc.isConnectingToInternet();
//		 if(!isconnected){
//		 // Internet Connection is not present
//		 alert.showAlertDialog(HomeActivity.this, "Internet Connection Error",
//		 "Please Connect to the Internet", false);
//		 // stop executing code by return
//		 return;
//		 }else if(){
//			 
//		 }

		location_searching = (EditText) findViewById(R.id.location_auto_search);
		btn_searching = (Button) findViewById(R.id.btn_auto_search);
		ab = getSupportActionBar();

		//starts here
		
		// We instantiate the MapView here, it's really important!
		Exchanger.mMapView = new MapView(this,"07QrqGLNNbvFFh9LUuMashT4Bukx3tMIwwfrOaA"); // TODO: Replace for// API Key!
		Exchanger.mMapView.setSatellite(true);
		controlmap = Exchanger.mMapView.getController();
		controlmap.animateTo(new GeoPoint(userlat,userlon));
		controlmap.setZoom(14);
//		me = new MyLocationOverlay(this, Exchanger.mMapView);
		// start here overlay
		newmapOverlays = Exchanger.mMapView.getOverlays();
		drawable = getResources().getDrawable(R.drawable.mark_red);
		useroverlaylocation = new AddUserLocationOverlay(drawable, h);
		gp = new GeoPoint(userlat, userlon);

		overlayitem = new OverlayItem(gp, "Your Choosen Location", "This is you");
		useroverlaylocation.addOverlay(overlayitem);		
		newmapOverlays.clear();
		newmapOverlays.add(useroverlaylocation);

		setupFragments();
		// addView();
		// We manually show the list Fragment.
		showFragment(mMapFragment);
		// set defaults for logo & home up
		ab.setDisplayHomeAsUpEnabled(showHomeUp);
		Intent intent = getIntent();
		String name = intent.getStringExtra("name");
		actionbar = getSupportActionBar();
		actionbar.setDisplayShowHomeEnabled(false);
		actionbar.setDisplayShowTitleEnabled(false);
		ActionItem nextItem = new ActionItem(ID_DOWN, "Settings",
				getResources().getDrawable(R.drawable.menu_down_arrow));
		ActionItem prevItem = new ActionItem(ID_UP, "About Us", getResources()
				.getDrawable(R.drawable.menu_up_arrow));
		ActionItem searchItem = new ActionItem(ID_SEARCH, "Help",
				getResources().getDrawable(R.drawable.menu_search));
		// use setSticky(true) to disable QuickAction dialog being dismissed
		// after an item is clicked
		prevItem.setSticky(true);
		nextItem.setSticky(true);
		final QuickAction quickAction = new QuickAction(this,
				QuickAction.VERTICAL);
		// add action items into QuickAction
		quickAction.addActionItem(nextItem);
		quickAction.addActionItem(prevItem);
		quickAction.addActionItem(searchItem);
		// Set listener for action item clicked
		quickAction
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					public void onItemClick(QuickAction source, int pos,
							int actionId) {
						ActionItem actionItem = quickAction.getActionItem(pos);
						// here we can filter which action item was clicked with
						// pos or actionId parameter
						if (actionId == ID_SEARCH) {
							Toast.makeText(getApplicationContext(),
									"Let's do some search action",
									Toast.LENGTH_SHORT).show();
						} else if (actionId == ID_INFO) {
							Toast.makeText(getApplicationContext(),
									"I have no info this time",
									Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(getApplicationContext(),
									actionItem.getTitle() + " selected",
									Toast.LENGTH_SHORT).show();
						}
					}
				});
		quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
			public void onDismiss() {
				Toast.makeText(getApplicationContext(), "Dismissed",
						Toast.LENGTH_SHORT).show();
			}
		});
		// set up list navigation
		ab.setListNavigationCallbacks(ArrayAdapter.createFromResource(this,
				R.array.sections, R.layout.sherlock_spinner_dropdown_item),
				new OnNavigationListener() {
					public boolean onNavigationItemSelected(int itemPosition,
							long itemId) {
						// FIXME add proper implementation
						if (itemPosition == 0) {
							Log.d(getClass().getName(),
									"Ignoring selection of dummy list item...");
						} else {
							Log.d(getClass().getName(),
									"Handling selection of actual list item...");
							// TODO: insert code to handle selection
						}
						return false;
					}

					public void onNothingSelected(AdapterView<?> anAdapterView) {
						// do nothing
					}
				});
		actionbar.setDisplayShowCustomEnabled(true);
		View actionbar_logIn = LayoutInflater.from(this).inflate(
				R.layout.action_custom1, null);
		spinnerIcon = (Button) actionbar_logIn.findViewById(R.id.button1);
		_logIn = (Button) actionbar_logIn.findViewById(R.id.login);
		logo = (Button) actionbar_logIn.findViewById(R.id.logo);
		_logout = (Button) actionbar_logIn.findViewById(R.id.button2);
		spinnerIcon.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				quickAction.show(v);
				quickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
			}
		});
		_logIn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (!islogin) {
					finish();
					startActivity(new Intent(getApplicationContext(),
							LoginActivity.class));
				}

				else {

					ActionItem nextItem = new ActionItem(ID_DOWN,
							"Go To Profile", getResources().getDrawable(
									R.drawable.menu_down_arrow));
					ActionItem prevItem = new ActionItem(ID_UP, "Log out",
							getResources()
									.getDrawable(R.drawable.menu_up_arrow));

					// use setSticky(true) to disable QuickAction dialog being
					// dismissed
					// after an item is clicked
					prevItem.setSticky(true);
					nextItem.setSticky(true);
					final QuickAction quickAction1 = new QuickAction(
							getApplicationContext(), QuickAction.VERTICAL);
					// add action items into QuickAction
					quickAction1.addActionItem(nextItem);
					quickAction1.addActionItem(prevItem);

					// Set listener for action item clicked
					quickAction1
							.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
								public void onItemClick(QuickAction source,
										int pos, int actionId) {
									ActionItem actionItem = quickAction1
											.getActionItem(pos);
									// here we can filter which action item was
									// clicked with
									// pos or actionId parameter
									if (actionId == ID_DOWN) {
										Toast.makeText(getApplicationContext(),
												"Go to Profile",
												Toast.LENGTH_SHORT).show();
										if (LoginActivity.PersonType
												.equals("Agent")) {
											
											Intent i = new Intent(
													getApplicationContext(),
													Agent.class);
											startActivity(i);
										} else if (LoginActivity.PersonType
												.equals("Administrator")) {

											Intent i = new Intent(
													getApplicationContext(),
													DashBoard.class);
											startActivity(i);
										} else {
											Intent i = new Intent(
													getApplicationContext(),
													Buyer.class);
											startActivity(i);
										}

									} else if (actionId == ID_UP) {
										Toast.makeText(getApplicationContext(),
												"Logging out",
												Toast.LENGTH_SHORT).show();

										islogin = false;
										finishActivity(0);
										startActivity(getIntent());
										
									} else {
										Toast.makeText(
												getApplicationContext(),
												actionItem.getTitle()
														+ " selected",
												Toast.LENGTH_SHORT).show();
									}
								}
							});
					quickAction1
							.setOnDismissListener(new QuickAction.OnDismissListener() {
								public void onDismiss() {
									Toast.makeText(getApplicationContext(),
											"Dismissed", Toast.LENGTH_SHORT)
											.show();
								}
							});

					quickAction1.show(v);
					quickAction1
							.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);

				}
			}
		});

		logo.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				quickAction.show(v);
				quickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);
			}
		});
		actionbar.setCustomView(actionbar_logIn);

		btn_searching.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				String loc_address = location_searching.getText().toString();
				String defaultaddress = "philippines";
				String finloc_address = loc_address + defaultaddress;
				if (loc_address != null && !loc_address.equals("")) {
					new GeoCodeAddress().execute(finloc_address);
				}

				actionbar.show();
			}
		});
		location_searching.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				actionbar.hide();
			}
		});
		new executeLoadWebService().execute();
	}

	/**
	 * Reset the filter spinner selection to 0 - which is ignored in
	 * onItemSelected() - so that a subsequent selection of another item is
	 * triggered, regardless of whether it's the same item that was selected
	 * previously.
	 */
	protected void resetSelection() {
		Log.d(getClass().getName(),
				"Resetting selection to 0 (i.e. 'please select' item).");
		mySpinner.setSelection(0);
	}

	/**
	 * This method does the setting up of the Fra gments. It basically checks if
	 * the fragments exist and if they do, we'll hide them. If the fragments
	 * don't exist, we create them, add them to the FragmentManager and hide
	 * them.
	 */
	private void setupFragments() {
		final FragmentTransaction ft = getSupportFragmentManager()
				.beginTransaction();
		/*
		 * If the activity is killed while in BG, it's possible that the
		 * fragment still remains in the FragmentManager, so, we don't need to
		 * add it again.
		 */
		mMapFragment = (MapFragment) getSupportFragmentManager()
				.findFragmentByTag(MapFragment.TAG);
		if (mMapFragment == null) {
			mMapFragment = new MapFragment();
			ft.add(R.id.fragment_container, mMapFragment, MapFragment.TAG);
		}
		ft.hide(mMapFragment);
		ft.commit();
	}

	private void showFragment(Fragment fragmentIn) {
		if (fragmentIn == null)
			return;
		final FragmentTransaction ft = getSupportFragmentManager()
				.beginTransaction();
		ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
		if (mVisible != null)
			ft.hide(mVisible);
		ft.show(fragmentIn).commit();
		mVisible = fragmentIn;
	}

	public static class Exchanger {
		// We will use this MapView always.
		public static MapView mMapView;
	}

	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		menu.add(0, AUTO_SEARCH, 0, "Search")
		.setIcon(R.drawable.search)
		.setShowAsAction(
				MenuItem.SHOW_AS_ACTION_IF_ROOM);

		menu.add(0, DIRECTION, 0, "Direction").setIcon(R.drawable.direction)
		.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

		menu.add(0, BOOKMARKS, 0, "Favorites").setIcon(R.drawable.bookmark)
		.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

		menu.add(0, HELP, 0, "Queries").setIcon(R.drawable.help)
		.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);	

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		super.onOptionsItemSelected(item);

		switch (item.getItemId()) {
		case DIRECTION:
			Toast.makeText(getBaseContext(), "Direction",
					Toast.LENGTH_LONG).show();
			routePath();
			break;

		case AUTO_SEARCH: {
			this.finishActivity(0);
			Toast.makeText(getBaseContext(), "autosearch",
					Toast.LENGTH_LONG).show();
			startActivity(new Intent(getApplicationContext(),
					MultipleSearching2.class));
			newmapOverlays.clear();
			break;
		}

		case BOOKMARKS: {
			Toast.makeText(getBaseContext(), "MAP SETTINGS",
					Toast.LENGTH_LONG).show();

			this.finishActivity(1);
			startActivity(new Intent(getApplicationContext(),
					MapSettings.class));
			newmapOverlays.clear();
			break;
		}
		case HELP: {
			Toast.makeText(getBaseContext(), "HELP",
					Toast.LENGTH_LONG).show();

			this.finish();
			startActivity(new Intent(getApplicationContext(),
					Help.class));
			newmapOverlays.clear();
			break;
		}

		}

		return true;
	}

	public void setHeader(String title, boolean btnHomeVisible,
			boolean btnFeedbackVisible) {
		ViewStub stub = (ViewStub) findViewById(R.id.vsHeader);
		View inflated = stub.inflate();
		TextView txtTitle = (TextView) inflated.findViewById(R.id.txtHeading);
		txtTitle.setText(title);
		Button btnHome = (Button) inflated.findViewById(R.id.btnHome);
		if (!btnHomeVisible)
			btnHome.setVisibility(View.INVISIBLE);
	}

	private void showDropDownNav() {
		ActionBar ab = getSupportActionBar();
		if (ab.getNavigationMode() != ActionBar.NAVIGATION_MODE_LIST) {
			ab.setDisplayShowTitleEnabled(false);
			ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		}
	}

	public static class MapFragment extends SherlockFragment {
		public static final String TAG = "mapFragment";

		public MapFragment() {
		}

		@Override
		public void onCreate(Bundle arg0) {
			super.onCreate(arg0);
			// setRetainInstance(true);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup vg,
				Bundle data) {
			Exchanger.mMapView.setClickable(true);
			Exchanger.mMapView.setBuiltInZoomControls(true);
			return Exchanger.mMapView;
		}
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	
	private class GeoCodeAddress extends AsyncTask<String, Void, List<Address>>{

		@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				pDialog = new ProgressDialog(HomeActivity.this);
				pDialog.setMessage(Html.fromHtml("<b></b><br/>Searching Locations..."));
				pDialog.setIndeterminate(false);
				pDialog.setCancelable(true);
				pDialog.show();
			}
		@Override
		protected List<Address> doInBackground(String... addressname) {
			// TODO Auto-generated method stub
			Geocoder geocoder = new Geocoder(getBaseContext());
			List<Address> addresses = null;
			
			try {
				// Getting a maximum of 3 Address that matches the input text
				addresses = geocoder.getFromLocationName(addressname[0], 3);
			} catch (IOException e) {
				e.printStackTrace();
			}			
			return addresses;
		}
		
		@Override
		protected void onPostExecute(final List<Address> addresses) {
			// TODO Auto-generated method stub
			if(pDialog!=null){
			pDialog.dismiss();
			}
			 if(addresses!=null || addresses.size()!=0){
			runOnUiThread(new Runnable(){
				public void run() {
					// TODO Auto-generated method stub

			       
					for(int i=0;i<addresses.size();i++){				
						
						Address address = (Address) addresses.get(i);
						
				        // Creating an instance of GeoPoint, to display in Google Map
				        GeoPoint p = new GeoPoint(
				                                  (int)(address.getLatitude()*1E6),
				                                  (int)(address.getLongitude()*1E6)
				                                 );
				        
				        String addressText = String.format("%s, %s",
			                    address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
			                    address.getCountryName());
				        
				        // Locate the first location
				        if(i==0)
				        
						//start here overlay
						newmapOverlays = Exchanger.mMapView.getOverlays();
						drawable = getResources().getDrawable(R.drawable.mark_red);
						useroverlaylocation = new AddUserLocationOverlay(drawable,h);
						gp = new GeoPoint(userlat,userlon);
						
						overlayitem = new OverlayItem(gp, "Your Choosen Location", "This is you");
						useroverlaylocation.addOverlay(overlayitem);		
						newmapOverlays.clear();
						newmapOverlays.add(useroverlaylocation);
						controlmap.animateTo(p);
				        controlmap.setZoom(14);			        			        				
				}
				}			
			});
			 }else if(addresses==null || addresses.size()==0){
					//Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
					alert.showAlertDialog(HomeActivity.this, "Searching Locations",
							"Sorry no locations found. Try to change location",
							false);
					// Redraws the map to clear the overlay
		    		

				}
	    		newmapOverlays.clear();
	    		controlmap.animateTo(new GeoPoint(10309416,123893509));
		        controlmap.setZoom(14);
			//Exchanger.mMapView.invalidate();

		}
		}
	
	public void loadWebService(){
		cws = new ConsumeWebService();
		 String data = cws.getAllProperty();
		 
		 try {

				JSONArray array = new JSONArray(data);
				
				for (int i = 0; i < array.length(); i++) {
					map = new HashMap<String, String>();
					
					JSONObject e = array.getJSONObject(i);
					map.put("property_id", e.getString(KEY_ID));
					map.put("property_name", e.getString(KEY_NAME));
					map.put("property_description", e.getString(KEY_DESCRIPTION));
					map.put("price", e.getString(KEY_PRICE));
					map.put("latitude", e.getString(KEY_LATITUDE));
					map.put("longitude", e.getString(KEY_LONGITUDE));
					map.put("address", e.getString(KEY_ADDRESS));
					map.put("type", e.getString(KEY_TYPE));
					map.put("image", e.getString(KEY_IMAGE));
					map.put("firstname", e.getString("firstname"));
					map.put("lastname", e.getString("lastname"));
					map.put("mobile", e.getString("mobile"));
					map.put("email", e.getString("email_address"));
										
					mylist.add(map);

				}
			} catch (JSONException e) {
				Log.e("log_tag", "Error parsing data " + e.toString()+"diri jud");
			}finally{
				
			}
	//	 Toast.makeText(getApplicationContext(), ""+mylist, Toast.LENGTH_LONG).show();		
	}
	//for loading web data then plot on map
	//for loading web data then plot on map
		public class executeLoadWebService extends AsyncTask<Void,Void,Void>{
		    public ProgressDialog dialog=new ProgressDialog(HomeActivity.this);
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
	            this.dialog.setMessage("Loading data...");
	            this.dialog.show();
	            
			}
			@Override
			protected Void doInBackground(Void... arg0) {
				// TODO Auto-generated method stub
				try{
					loadWebService();
				}catch(Exception e){
					//Log.e("error",e.getMessage());
				}
				return null;
			}		
			@Override
			protected void onPostExecute(Void result) {
				// TODO Auto-generated method stubsi
				newmapOverlays = Exchanger.mMapView.getOverlays();
		    	if (this.dialog!=null) {
		            this.dialog.dismiss();	            
		        }	    	 
//		    	Toast.makeText(getApplicationContext(), ""+mylist, Toast.LENGTH_LONG).show();
		    	if(!mylist.isEmpty()){
				runOnUiThread(new Runnable(){
					public void run() {	
				    	for(int i = 0; i<mylist.size(); i++){
				    		HashMap<String, String> map = mylist.get(i); 		
				    		String tr1 = (String) map.get(KEY_LATITUDE);
				    		String tr2 = (String) map.get(KEY_LONGITUDE);
							String pname = map.get(KEY_NAME);
							String pdescription = map.get(KEY_DESCRIPTION);
							String paddress = map.get(KEY_ADDRESS);
							String pimage = map.get("image");
							String ptype = map.get("type");
							String pprice = map.get("price");
							String pindex = map.get(KEY_ID).toString();
							String pagent = map.get("firstname");
							String pcontact = map.get("mobile");
				    		if(!tr1.matches("") && !tr2.matches("")){
				    			int lat1 = Integer.valueOf((String) tr1);
				    			int  long2= Integer.valueOf((String) tr2);
//				    			double cinttr1 = (double) lat1/1E6;
//				    			double cinttr2 = (double) long2/1E6;

								gp = new GeoPoint(lat1, long2);
								minLat  = (int) Math.min( gp.getLatitudeE6(), minLat );
							    minLong = (int) Math.min( gp.getLongitudeE6(), minLong);
							    maxLat  = (int) Math.max( gp.getLatitudeE6(), maxLat );
							    maxLong = (int) Math.max( gp.getLongitudeE6(), maxLong );
								if(ptype.equalsIgnoreCase("building")){
									drawable = getResources().getDrawable(R.drawable.building2);
								}else if(ptype.equalsIgnoreCase("house")){
									drawable = getResources().getDrawable(R.drawable.house2);
								}else if(ptype.equalsIgnoreCase("subdivision")){
									drawable = getResources().getDrawable(R.drawable.subdivision2);
								}else if(ptype.equalsIgnoreCase("condominium")){
									drawable = getResources().getDrawable(R.drawable.building2);
								}
							    
//						    	drawable = getResources().getDrawable(R.drawable.building2);
						    	newitemizedOverlay2 = new CustomItemizedOverlay<CustomOverlayItem>(drawable, Exchanger.mMapView);
								  overlayItem3 = new CustomOverlayItem(gp, ""+pname, 
											"Description: "+pdescription,"Address: "+paddress,pindex,pprice,ptype,pagent,pimage,pcontact);
											newitemizedOverlay2.addOverlay(overlayItem3);
											newmapOverlays.add(newitemizedOverlay2);
											newitemizedOverlay2.populateNow();	
//				    			Toast.makeText(getApplicationContext(), "Converted int lat "+lat1+"Converted int lon "+long2, Toast.LENGTH_LONG).show();
//				    			Toast.makeText(getApplicationContext(), "Converted double lat "+cinttr1+"Converted double lon "+cinttr2, Toast.LENGTH_LONG).show();
				    			
				    		}
//				    		Toast.makeText(getApplicationContext(), "data lat "+tr1+" data lon "+tr2, Toast.LENGTH_LONG).show();
				    	}
					}			
				});
		    	}else if(mylist.isEmpty()){
		    		alert.showAlertDialog(HomeActivity.this, "Internet Connection Error",
							"No property found. Try to check your internet connection",
							false);	    		
		    	}
				controlmap.zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
				controlmap.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
				Exchanger.mMapView.invalidate();				
				
		    	
		    	}	    	    	    			
		}

		//for autosearching inig tap
		public void executeAutoSearch(final int latitude, final int longitude){
			
			newmapOverlays = Exchanger.mMapView.getOverlays();
			drawable = getResources().getDrawable(R.drawable.mark_red);
			taplocation = new AddTapLocationOverlay(drawable, h, this);
			gp = new GeoPoint(latitude,longitude);
			
			overlayitem = new OverlayItem(gp, "Your Choosen Location", "This is you");
			taplocation.addOverlay(overlayitem);		
			newmapOverlays.clear();
			newmapOverlays.add(taplocation);
			taplocation.populateNow();
			controlmap.setZoom(14);
			
			for(int i = 0; i<mylist.size(); i++){
				HashMap<String, String> map = mylist.get(i);			
			    		String wslat = (String) map.get(KEY_LATITUDE);
			    		String wslon = (String) map.get(KEY_LONGITUDE);
						String pname = map.get(KEY_NAME);
						String pdescription = map.get(KEY_DESCRIPTION);
						String paddress = map.get(KEY_ADDRESS);
						String pimage = map.get(KEY_IMAGE);
						String ptype = map.get(KEY_TYPE);
						String pprice = map.get(KEY_PRICE);
						String pindex = map.get(KEY_ID).toString();
						String pagent = map.get("firstname");
						String pcontact = map.get("mobile");
				if(!wslat.matches("") && !wslon.matches("")){
					int clat = Integer.valueOf(wslat).intValue();
					int clon = Integer.valueOf(wslon).intValue();
					
					
					double distance = new ComputeDistance().distanceFromList(latitude, longitude, clat, clon);
					double constantd = 600;
					minLat  = (int) Math.min( gp.getLatitudeE6(), minLat );
				    minLong = (int) Math.min( gp.getLongitudeE6(), minLong);
				    maxLat  = (int) Math.max( gp.getLatitudeE6(), maxLat );
				    maxLong = (int) Math.max( gp.getLongitudeE6(), maxLong );
				    
				    double sdlat = (double) latitude/1E6;
				    double sdlon = (double) longitude/1E6;
				    
				    double dclat = (double) clat/1E6;
				    double dclon = (double) clon/1E6;
				    

				    if(distance<=constantd){
				    	gp = new GeoPoint(clat,clon);			    	
						if(ptype.equalsIgnoreCase("building")){
							drawable = getResources().getDrawable(R.drawable.building2);
						}else if(ptype.equalsIgnoreCase("house")){
							drawable = getResources().getDrawable(R.drawable.house2);
						}else if(ptype.equalsIgnoreCase("subdivision")){
							drawable = getResources().getDrawable(R.drawable.subdivision2);
						}else if(ptype.equalsIgnoreCase("condominium")){
							drawable = getResources().getDrawable(R.drawable.building2);
						}
						GeoPoint gpt1 = new GeoPoint(latitude,longitude);
						GeoPoint gpt2 = new GeoPoint(clat,clon);
						
						Route route = directions(gpt1, gpt2);
						
						RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE);
						  newitemizedOverlay2 = new CustomItemizedOverlay<CustomOverlayItem>(drawable, Exchanger.mMapView);
						  overlayItem3 = new CustomOverlayItem(gp, ""+pname, 
									"Description: "+pdescription,"Address: "+paddress,pindex,pprice,ptype,pagent,pcontact,
									"http://ia.media-imdb.com/images/M/MV5BMjAyNjk5Njk0MV5BMl5BanBnXkFtZTcwOTA4MjIyMQ@@._V1._SX40_CR0,0,40,54_.jpg");					  
						  newitemizedOverlay2.addOverlay(overlayItem3);
						  newmapOverlays.add(routeOverlay);
						  newmapOverlays.add(newitemizedOverlay2);
						  newitemizedOverlay2.populateNow();					
				    }
				}
			}
			
			controlmap.zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
			controlmap.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
			Exchanger.mMapView.invalidate();

		}
		public void routePath(){
			
			AsyncTask newtask = new AsyncTask(){
			    public ProgressDialog dialog=new ProgressDialog(HomeActivity.this);
			    Route route;
			    RouteOverlay routeOverlay; 
				@Override
				protected void onPreExecute() {
					// TODO Auto-generated method stub
		            this.dialog.setMessage("Loading direction...");
		            this.dialog.show();
				}
				
				@Override
				protected Object doInBackground(Object... params) {
					// TODO Auto-generated method stub
			
					try{
						for(int i = 0; i<mylist.size(); i++){
							HashMap<String, String> map = mylist.get(i);			
				    		String wslat = (String) map.get(KEY_LATITUDE);
				    		String wslon = (String) map.get(KEY_LONGITUDE);
							String pname = map.get(KEY_NAME);
							String pdescription = map.get(KEY_DESCRIPTION);
							String paddress = map.get(KEY_ADDRESS);
							String pimage = map.get(KEY_IMAGE);
							String ptype = map.get(KEY_TYPE);
							String pprice = map.get(KEY_PRICE);
							String pindex = map.get(KEY_ID).toString();
							String pagent = map.get("firstname");
							String pcontact = map.get("mobile");
							
							if(!wslat.matches("") && !wslon.matches("")){
								int clat = Integer.valueOf(wslat).intValue();
								int clon = Integer.valueOf(wslon).intValue();
								final GeoPoint gpt1 = new GeoPoint(userlat,userlon);
								final GeoPoint gpt2 = new GeoPoint(clat,clon);
									
								if(ptype.equalsIgnoreCase("building")){
									drawable = getResources().getDrawable(R.drawable.building2);
								}else if(ptype.equalsIgnoreCase("house")){
									drawable = getResources().getDrawable(R.drawable.house2);
								}else if(ptype.equalsIgnoreCase("subdivision")){
									drawable = getResources().getDrawable(R.drawable.subdivision2);
								}else if(ptype.equalsIgnoreCase("condominium")){
									drawable = getResources().getDrawable(R.drawable.building2);
								}
						    	routeOverlay = new RouteOverlay(route, Color.BLUE);
								
								  newitemizedOverlay2 = new CustomItemizedOverlay<CustomOverlayItem>(drawable, Exchanger.mMapView);
								  overlayItem3 = new CustomOverlayItem(gp, ""+pname, 
											"Description: "+pdescription,"Address: "+paddress,pindex,pprice,ptype,pagent,pcontact,
											"http://ia.media-imdb.com/images/M/MV5BMjAyNjk5Njk0MV5BMl5BanBnXkFtZTcwOTA4MjIyMQ@@._V1._SX40_CR0,0,40,54_.jpg");					  
								  newitemizedOverlay2.addOverlay(overlayItem3);
								  newmapOverlays.add(routeOverlay);
								  newmapOverlays.add(newitemizedOverlay2);
								  newitemizedOverlay2.populateNow();										
							}
						
						}
					}catch(Exception ie){
						Log.e("error",ie.getMessage());
					}
					return null;
				}
				
				@Override
				protected void onPostExecute(Object result) {
					// TODO Auto-generated method stub
					
			    	if (this.dialog!=null) {
			            this.dialog.dismiss();	            
			        }
			    	
					Exchanger.mMapView.invalidate();				
					controlmap.animateTo(new GeoPoint(userlat,userlon));
					controlmap.setZoom(14);	
				}
				
			};	
				
				newtask.execute();
				
		}
		
		private Route directions(final GeoPoint start, final GeoPoint dest) {
		    Parser parser;
		    //https://developers.google.com/maps/documentation/directions/#JSON <- get api
		    String jsonURL = "http://maps.googleapis.com/maps/api/directions/json?";
		    final StringBuffer sBuf = new StringBuffer(jsonURL);
		    sBuf.append("origin=");
		    sBuf.append(start.getLatitudeE6()/1E6);
		    sBuf.append(',');
		    sBuf.append(start.getLongitudeE6()/1E6);
		    sBuf.append("&destination=");
		    sBuf.append(dest.getLatitudeE6()/1E6);
		    sBuf.append(',');
		    sBuf.append(dest.getLongitudeE6()/1E6);
		    sBuf.append("&sensor=true&mode=driving");
		    parser = new GoogleParser(sBuf.toString());
		    Route r =  parser.parse();
		    return r;
		}
		
		@Override
		public void onBackPressed() {
			HomeActivity.this.finish();
		}
	}
